/**
 * 
 */
package com.skood.platform.util;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.skood.common.domain.Sorter;

/**
 * @author keege
 * @date 2014-1-4
 * service调用的相关工具方法
 */
public class ServiceUtils {

	private static Logger LOG = LoggerFactory.getLogger(ServiceUtils.class);
	public static void main(String[] args){
		String sortParameters = "[{\"property\":\"name\",\"direction\":\"DESC\"},{\"property\":\"nickName\",\"direction\":\"ASC\"}]";
		List<Sorter> sorterList = JSON.parseArray(sortParameters, Sorter.class);
		System.out.println(sorterList);
	}
	/**
	 * 
	 * @param resultMap 对应查询mybatis<select resultMap>的全名“com.skood.security.dao.UserDAO.userMap”
	 * @param sortParameters extjs传入的查询条件，对应searchModel.sort etc:'[{"property":"name","direction":"DESC"},{"property":"nickName","direction":"ASC"}]'
	 * @return
	 */
	public static String convertOrderSql(String resultMap,String sortParameters){
		resultMap = StringUtils.trim(resultMap);
		sortParameters = StringUtils.trim(sortParameters);
		if(StringUtils.isEmpty(resultMap)||StringUtils.isEmpty(sortParameters)){
			return null;
		}
		
		SqlSessionFactory sqlSessionFactory=SpringApplicationContextHolder.getBean("sqlSessionFactory");
		Configuration configuration = sqlSessionFactory.getConfiguration();
		ResultMap userMap = configuration.getResultMap(resultMap);
		List<ResultMapping> resultMappingList = userMap.getResultMappings();
		
		List<Sorter> sorterList;
		try{
			sorterList = JSON.parseArray(sortParameters, Sorter.class);
		}catch(JSONException e){
			LOG.error("排序参数{}格式不正确{}",sortParameters,e.getMessage());
			
			return null;
		}
		
		
		StringBuilder sorterData = new StringBuilder();
		
		for(Sorter sorter:sorterList){

			String columnName = null;
			for(ResultMapping resultMapping:resultMappingList){
				if(resultMapping.getProperty().equals(sorter.getProperty())){
					columnName = resultMapping.getColumn();
					break;
				}
			}
			if(columnName==null){
				continue;
			}
			/*if(!StringUtils.isEmpty(sorterData.toString())){
				sorterData.append(" , ");
			}*/
			sorterData.append(columnName+ " "+sorter.getDirection());
			sorterData.append(" , ");
		}
		
		return sorterData.toString();
	}
}
